1.14 单元测试

1.14.1 配置

修改配置文件pom.xml,一般使用idea新建一个SpringBoot web项目时,一般都会自动引入此依赖,如果没有,请手动添加依赖。

1
2
3
4
5
6
7
8
9
10
11
12

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

1.14.2 编写测试代码

新建一个测试类,测试service中的两个方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

package com.zone7.demo.helloworld;

import com.zone7.demo.helloworld.sys.service.SysUserService;
import com.zone7.demo.helloworld.sys.vo.SysUserVo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloworldApplicationTests {
@Autowired
private SysUserService sysUserService;

@Test
public void testFindByName() {
List<SysUserVo> users = sysUserService.findByName("zone7");
System.out.println("查询到用户数:"+users.size());

}
@Test
public void testSave() {
SysUserVo user = new SysUserVo();
user.setName("testuser");
user.setPassword("123");
user.setPhone("111111111111");
sysUserService.save(user);
List<SysUserVo> users = sysUserService.findByName("testuser");
Assert.notEmpty(users,"保存失败");
}


}

代码中使用@Autowired引入你想测试的类,在测试方法上加@Test注解。

1.14.3 执行单元测试

通过点击方法前的小标执行测试,操作如下图所示:
单元测试

1.14.4 打包测试

开发完成之后,有可能我们已经写了一百多个测试用例类,我并不能每个类都点击进去一个个执行,SpringBoot提供了打包测试的方式:用一个类,把所有的测试类整理进去,然后直接运行这个类,所有的测试类都会执行。

我这里建了两个测试类,分别是EntFileTest,EntFileTest2,现在我打包进TestSuits,让他们一次运行,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

package com.zone7.demo.helloworld;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
* Created by zone7
* Date 2019/6/2
* Description:打包测试
*/

@RunWith(Suite.class)
@Suite.SuiteClasses({SysuserControllerTests.class,SysuserServiceTests.class})
public class TestSuits {

//不用写代码,只需要类顶级注解即可
}

当一个测试类中有1个方法暂时不想测测试,想在打包测试过程中跳过该方法,怎么办?这里有一个忽略注解@Ignore(“not ready yet”),写在方法上,可以忽略这个测试方法,写在类上,可以忽略这个类。
单元测试
此时,运行打包测试类TestSuits,SysuserServiceTests.testFindByName()方法就会忽略执行。